package org.simplespringframework.mvc;

import org.simplespringframework.BeanContainer;
import org.simplespringframework.aop.AspectWeaver;
import org.simplespringframework.inject.DependencyInjector;
import org.simplespringframework.mvc.processor.RequestProcessor;
import org.simplespringframework.mvc.processor.impl.ControllerRequestProcessor;
import org.simplespringframework.mvc.processor.impl.JspRequestProcessor;
import org.simplespringframework.mvc.processor.impl.PreRequestProcessor;
import org.simplespringframework.mvc.processor.impl.StaticResourceRequestProcessor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: simpleframework
 * @BelongsPackage: com.xshang.controller
 * @Author: xshang
 * @CreateTime: 2023-06-23  17:59
 * @Description: TODO
 * @Version: 1.0
 */
@WebServlet("/*")   // 拦截所有请求
public class DispatcherServlet extends HttpServlet {

    private static final List<RequestProcessor> PROCESSOR = new ArrayList<>();

    @Override
    public void init() {
        // 初始化容器
        BeanContainer beanContainer = BeanContainer.getInstance();
        beanContainer.loadBeans("com.xshang");
        new AspectWeaver().doAop();
        new DependencyInjector().doIoc();
        // 初始化请求处理器责任链
        PROCESSOR.add(new PreRequestProcessor());
        PROCESSOR.add(new StaticResourceRequestProcessor(getServletContext()));
        PROCESSOR.add(new JspRequestProcessor(getServletContext()));
        PROCESSOR.add(new ControllerRequestProcessor());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.创建责任链对象实例
        RequestProcessorChain requestProcessorChain = new RequestProcessorChain(PROCESSOR.iterator(), req, resp);
        // 2.通过责任链模式来依次调用请求处理器对请求进行处理
        requestProcessorChain.doRequestProcessorChain();
        // 3.对处理结果进行渲染
        requestProcessorChain.doRender();

    }
}
